
package com.ttomato.game.mrnom;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

public class Snake {
    public static final int UP = 0;
    public static final int LEFT = 1;
    public static final int DOWN = 2;
    public static final int RIGHT = 3;

    public List<SnakePart> mParts = new ArrayList<SnakePart>();

    public int mDirection;

    public Snake() {
        mDirection = UP;
        mParts.add(new SnakePart(5, 6));
        mParts.add(new SnakePart(5, 7));
        mParts.add(new SnakePart(5, 8));
        
        ByteBuffer buffer = ByteBuffer.allocateDirect(64);
    }

    public void turnLeft() {
        mDirection += 1;
        if (mDirection > RIGHT) {
            mDirection = UP;
        }
    }

    public void turnRight() {
        mDirection -= 1;
        if (mDirection < UP) {
            mDirection = RIGHT;
        }
    }

    public void eat() {
        SnakePart endPart = mParts.get(mParts.size() - 1);
        mParts.add(new SnakePart(endPart.mX, endPart.mY));
    }

    public void advance() {
        SnakePart head = mParts.get(0);

        int len = mParts.size() - 1;

        for (int i = len; i > 0; i--) {
            SnakePart before = mParts.get(i - 1);
            SnakePart part = mParts.get(i);
            part.mX = before.mX;
            part.mY = before.mY;
        }

        if (mDirection == UP) {
            head.mY -= 1;
        }
        if (mDirection == LEFT) {
            head.mX -= 1;
        }
        if (mDirection == DOWN) {
            head.mY += 1;
        }
        if (mDirection == RIGHT) {
            head.mX += 1;
        }

        if (head.mX < 0) {
            head.mX = 9;
        }
        if (head.mX > 9) {
            head.mX = 0;
        }
        if (head.mY < 0) {
            head.mY = 12;
        }
        if (head.mY > 12) {
            head.mY = 0;
        }

    }

    public boolean checkBitten() {
        int len = mParts.size() - 1;
        SnakePart head = mParts.get(0);
        SnakePart part;
        for (int i = 1; i < len; i++) {
            part = mParts.get(i);
            if (head.mX == part.mX && head.mY == part.mY) {
                return true;
            }
        }
        return false;
    }

}
